//uses jquery
//uses jquery.md5


var kavadenn = kavadenn || {};
kavadenn.flickrServiceSettings = {
  "apiKey": "e40073c81ceffaa294c7b06eb6c4b092",
  "apiSecret": "a5ed2e5c56ff055e",  
  "token":null,
  "pageSize": 20
};


function getFrob(handler){
  $.getJSON("/photos/flickr/getfrob/", handler);
}

function buildFlickrAuthenticationUrl(frob){
  var apiKey=kavadenn.flickrServiceSettings["apiKey"];
  var perms="read";
  var apiSecret=kavadenn.flickrServiceSettings["apiSecret"];
  var signature = $.md5(
    apiSecret+"api_key"+apiKey+"frob"+frob+"perms"+perms
  );
  return "http://flickr.com/services/auth/?api_key="+apiKey+"&frob="+frob+"&perms="+perms+"&api_sig="+signature;  
}

function getFlickrToken(frob,handler){
  var url = "/photos/flickr/gettoken/?frob="+frob;
  $.getJSON(url,function(d){
    kavadenn.flickrServiceSettings["token"] = d.token;
    if(handler)handler(d);
  });
}

/*
  Flickr request object
*/
kavadenn.FlickrRequest = function(searchTerm, handleGotData, settings){
  // searchTerm
  /*
      { 
        "search_type" : "general" | "user_photos" default="general"
        "text": default=null 
      }
  */
  // settings 
  /*
    { "exclude_list": default=[] }
  */
  
  var defaultSearchTerm = {
    "search_type": "general",
    "text": null
  };
  this._searchTerm = {};
  $.extend(this._searchTerm, defaultSearchTerm, searchTerm);
  
  
  var defaultSettings = {
    "exclude_list":[],
    "pageSize": kavadenn.flickrServiceSettings["pageSize"]
  };
  var _settings = {};
  
  if(settings["exclude_list"] != null){
    var originalList = settings["exclude_list"];
    settings["exclude_list"] = [];
    for(var i=0; i<originalList.length; i++)
      settings["exclude_list"].push(originalList[i]);
  }
  
  $.extend(_settings, defaultSettings, settings);
  this.getSetting = function(key) { return _settings[key]; }
  
  var _handleGotData = handleGotData;
  this.getDataHandler = function(){return _handleGotData;}

  
  this._currentPage = 1;
  this._hasMore = false
  this._placeId = null;
  this._triedPlaceSearch = false;
  
  this._retries = 0;
}

kavadenn.FlickrRequest.prototype.execute = function(){
  this._retries++;
  try{
    console.log("talking to flickr; try #" + this._retries);
  }catch(x){}

  if(!this._placeId && !this._triedPlaceSearch){
    this._tryFindingPlace();
  }else{
    $.getJSON(this._url(), this._bindCallback(this._handleImagesFound));
  }
}

kavadenn.FlickrRequest.prototype.hasMore = function(){
  return this._hasMore;  
}

kavadenn.FlickrRequest.prototype._tryFindingPlace = function(){
  if(this._searchTerm["search_type"] != "general"){
    this._placeId = null;
    this._triedPlaceSearch = true;
    return;
  }
  
  var searchTerm = this._searchTerm["text"];
  var apiKey = kavadenn.flickrServiceSettings["apiKey"];
  $.getJSON(
    'http://api.flickr.com/services/rest/?method=flickr.places.find&api_key='+ apiKey + "&query=" + searchTerm + "&format=json&jsoncallback=?",
    this._bindCallback(this._foundPlace)
  );
}

kavadenn.FlickrRequest.prototype._foundPlace = function(d){
  this._triedPlaceSearch = true;
  if(d.stat == "ok"){
    if(d.places.place.length != 0) 
      this._placeId = d.places.place[0].place_id;
  }
  
  $.getJSON(this._url(), this._bindCallback(this._handleImagesFound));
}

kavadenn.FlickrRequest.prototype._thumbImageUrl = function(farm,server,id,secret){
  return 'http://farm' + farm + '.static.flickr.com/' + server + '/' + id + '_' + secret + '_s.jpg';
}

kavadenn.FlickrRequest.prototype._mediumImageUrl = function(farm,server,id,secret){
  return 'http://farm' + farm + '.static.flickr.com/' + server + '/' + id + '_' + secret + '_z.jpg';
}

kavadenn.FlickrRequest.prototype._originalImageUrl = function(farm,server,id,secret){
  return 'http://farm' + farm + '.static.flickr.com/' + server + '/' + id + '_' + secret + '_o.jpg';
}


kavadenn.FlickrRequest.prototype._url = function(){
  try{
    console.log("building flickr search url, terms are:");
    console.log(this._searchTerm);
  }catch(x){}
  
  
  var perPage = this.getSetting("pageSize");  
  var page = this._currentPage; 
  var apiKey = kavadenn.flickrServiceSettings["apiKey"];
  
  if(this._searchTerm["search_type"] == "general"){
    if(!this._placeId){
      var searchTerm = this._searchTerm["text"];
      return 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key='+ apiKey +'&per_page=' + perPage + '&page=' + page + '&text=' + searchTerm + "&format=json&jsoncallback=?";      
    }else{
      return 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key='+ apiKey +'&per_page=' + perPage + '&page=' + page + '&place_id=' + this._placeId + "&format=json&jsoncallback=?";
    }
  }
  
  if(this._searchTerm["search_type"] == "user_photos"){ 
    var signature = $.md5(
      kavadenn.flickrServiceSettings["apiSecret"]+
      "api_key"+apiKey+
      "auth_token"+kavadenn.flickrServiceSettings["token"]+
      "formatjson"+
      "methodflickr.people.getPhotos"+
      "nojsoncallback1"+
      "page"+page+
      "per_page"+perPage+
      "user_idme"
      
    );
    return 'http://api.flickr.com/services/rest/?method=flickr.people.getPhotos&api_sig='+ signature +'&api_key='+ apiKey +"&auth_token="+kavadenn.flickrServiceSettings["token"]+'&per_page=' + perPage + '&page=' + page + '&user_id=me' + "&format=json&nojsoncallback=1";
  }
  
  return null;
}

kavadenn.FlickrRequest.prototype._handleImagesFound = function(d) {
  if(d.stat == "ok"){
    //sometimes we get search results that should have photos but
    //instead contains an empty array
    if((parseInt(d.photos.total)!=0) && (d.photos.photo.length==0)){
      if(this._retries < 3){
        this.execute();
        return;
      }       
    }
    
    this._retries = 0;
    
    var r = [];
    var excludeList = this.getSetting("exclude_list");
    
    $.each(d.photos.photo,
        this._bindCallback(function(index, i) {
          var item = {}; 
          $.extend(item, {"thumb":this._thumbImageUrl(i.farm,i.server,i.id,i.secret),
              "medium":this._mediumImageUrl(i.farm,i.server,i.id,i.secret),
              "original":this._originalImageUrl(i.farm,i.server,i.id,i.secret)           
            }, i);
          
          //make sure current image is not within the exclusion list
          if(-1 == jQuery.inArray(item.thumb, excludeList)){
            r.push(item);
            excludeList.push(item.thumb);
          }
              
        }));
    
    
    this._hasMore = this._currentPage < d.photos.pages;
    this._currentPage++;
    
    var dataHandler = this.getDataHandler();
    if(dataHandler) dataHandler(r);
  }
}

kavadenn.FlickrRequest.prototype._bindCallback = function(callback) {
    //utility method to bind callback methods to the object instance
    var objSelf = this;
    return (function() { return (callback.apply(objSelf, arguments)); });
}
